package com.luo.demo;

import com.luo.mapper.UserMapper;
import com.luo.pojo.User;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

//Servlet测试demo
@WebServlet("/loginServlet")
public class LoginDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        resp.setContentType("text/json;charset=utf-8");
        req.setCharacterEncoding("UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        SqlSession session = util00.useSqlSessionFactory().openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        User user = mapper.selectUser(username, password);

        //输出测试
        System.out.println(user != null);
        System.out.println("username:" + username);
        System.out.println("password:" + password);

        if (user != null) {

            //输出测试
            System.out.println("post:" + user.getUserPost());
            System.out.println("classid:" + user.getUserClassId());
            System.out.println("sex:" + user.getUserSex());
            System.out.println("age:" + user.getUserAge());
            System.out.println("birthday:" + user.getUserBirthday());

            //存储到Session中
            //1. 获取Session对象
            HttpSession sess = req.getSession();
            //2. 存储数据
            sess.setAttribute("id", user.getId());
            sess.setAttribute("username", user.getUserName());
            sess.setAttribute("password", user.getUserPassword());
            sess.setAttribute("post", user.getUserPost());
            sess.setAttribute("classid", user.getUserClassId());
            sess.setAttribute("sex", user.getUserSex());
            sess.setAttribute("age", user.getUserAge());
            sess.setAttribute("birthday", user.getUserBirthday());
            writer.write("success");
        } else {
            writer.write("failure");
        }
        session.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
